<?php

namespace App\Models;

use App\Models\Base;
use Illuminate\Database\Eloquent\SoftDeletes;
use DB;
use File;

class Article extends Base
{
    protected $table = 'article';
    protected $hidden = ['add_uid','deleted_at'];
    public $category_arr = array(1=>'x',2=>'xx',3=>'xx',4=>'xx',5=>'xx',6=>'xx');

    use SoftDeletes;

    public function add_data($data){
        // 如果没有描述;则截取文章内容的前200字作为描述
        if (empty($data['description'])) {
            $description = preg_replace(array('/[~*>#-]*/', '/!?\[.*\]\(.*\)/', '/\[.*\]/'), '', $data['content']);
            $data['description'] = re_substr($description, 0, 200, true);
        }
        // 更新封面
        if (!empty($data['cover'])) {
            $new_path = str_replace('temp','article',$data['cover']);
            try {
                File::move(public_path($data['cover']),$new_path);
                $data['cover'] = $new_path;
            } catch (\Exception $e) {
                return false;
            }
        }
        //添加数据
        $result=$this
            ->create($data)
            ->id;
        if ($result) {
            return $result;
        }else{
            return false;
        }
    }

    public function edit_data($code,$data){
        $result = $this->where('code',$code)->update($data);
        if (!$result) return false;
        return true;
    }

    public function getDataByCode($code,$is_edit=0){
        $result = $this
            ->where('code',$code)
            ->first();
        if (!$result) return false;
        if ($result->keywords) {
            $result->keywords = explode(',',$result->keywords);
        }else{
            $result->keywords = [];
        }
        if ($is_edit) {
            return $result;
        }
        $result->add_time = timeAgo($result->updated_at);
        return $result;
    }

    public function getList($params,$pageSize=20){
        $tag = array_key_exists('tag',$params)?$params['tag']:false;
        $folder_id = array_key_exists('folder_id',$params)?$params['folder_id']:false;
        $publish = array_key_exists('publish',$params)?$params['publish']:false;
        $search = array_key_exists('search',$params)?$params['search']:false;
        if ($search&&$tag) $tag=false; // 并存条件
        $result = $this
                    ->select('article.id','article.folder_id','article.description','article.code','article.title','article.keywords','article.view','article.recommend','article.add_uid','article.publish','article.updated_at','article.created_at','admins.nick_name as add_uid_text')
                    ->when($folder_id,function($query) use($folder_id){
                        $query->where('folder_id',$folder_id);
                    })
                    ->when($publish,function($query) use($publish){
                        $query->where('publish',$publish);
                    })
                    ->when($search,function($query) use($search){
                        $query->whereRaw("(title like '%".$search."%' or FIND_IN_SET('".$search."',keywords))");
                    })
                    ->when($tag,function($query) use($tag){
                        $query->whereRaw('FIND_IN_SET(?,keywords)', [$tag]);
                    })
                    ->leftJoin('admins','admins.id','article.add_uid')
                    ->orderBy('updated_at','desc')
                    ->paginate($pageSize);
        if ($result) {
            $res_arr = $result->toArray();
            $data = $res_arr['data'];
            foreach ($data as $k => $v) {
                $data[$k]['updated_at'] = briefTime($data[$k]['updated_at']);
                $data[$k]['created_at'] = briefTime($data[$k]['created_at']);
                if ($data[$k]['keywords']) {
                    $data[$k]['keywords_arr'] = explode(',',$data[$k]['keywords']);
                }else {
                    $data[$k]['keywords_arr'] = [];
                }
            }
            $res_arr['data'] = $data;
            return $res_arr;
        }else{
            return false;
        }
    }

    public function delData($code){
        $result = $this->where('code',$code)->delete();
        return $result;
    }

}
